package cn.kxlove.zhbj.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * @author kxlove 16/1/28 14:48
 */
public class HorizontalScrollViewPager extends ViewPager {
    private int startX;
    private int startY;

    public HorizontalScrollViewPager(Context context) {
        super(context);
    }

    public HorizontalScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) ev.getX();
                startY = (int) ev.getY();
                getParent().requestDisallowInterceptTouchEvent(true);// 不要拦截
                break;
            case MotionEvent.ACTION_MOVE:
                int endX = (int) ev.getX();
                int endY = (int) ev.getY();

                int dx = endX - startX;
                int dy = endY - startY;

                if (Math.abs(dx) > Math.abs(dy)) {
                    // 左右滑动
                    if (dx > 0) {// 向右滑动
                        if (getCurrentItem() == 0) {
                            getParent().requestDisallowInterceptTouchEvent(false);// 需要拦截
                        }
                    } else {// 向左滑动
                        int count = getAdapter().getCount();// item总数
                        if (getCurrentItem() == count - 1) {
                            getParent().requestDisallowInterceptTouchEvent(false);// 需要拦截
                        }
                    }
                } else {
                    // 上下滑动
                    getParent().requestDisallowInterceptTouchEvent(false);// 需要拦截
                }

                break;

            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
}
